package com.eshopkeeper.core.util;

import com.eshopkeeper.core.util.yunzhi.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.Random;

/**
 * 常用公共方法
 */
@Service("commonUtil")
public class CommonUtil {
	private static final Logger logger = Logger.getLogger(CommonUtil.class);
	 
	/**
	 * 获取客户端真实IP
	 * 
	 * @throws Exception
	 */
	public static String getClientIP(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个ip值，第一个ip才是真实ip
			int index = ip.indexOf(",");
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		}
		ip = request.getHeader("X-Real-IP");
		if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			return ip;
		}
		return request.getRemoteAddr();
	}
	
	/**
	 * 获取随机验证码:随机产生的4位数字
	 */
	public static String getRandomCode_Four() {
		// 获取验证码
		String randomCode = "";
		// 验证码字符个数
		int codeCount = 4;
		// 创建一个随机数生成器类
		Random random = new Random();
		// 随机产生codeCount数字的验证码
		for (int i = 0; i < codeCount; i++) {
			// 得到随机产生的验证码数字
			String strRand = String.valueOf(random.nextInt(10));
			randomCode += strRand;
		}
		return randomCode;
	}
	
	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPostByHttp(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			conn.setConnectTimeout(120000);
			conn.setReadTimeout(120000);
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Accept-Charset", "UTF-8");
			conn.setRequestProperty("contentType", "UTF-8");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			logger.error("发送Http的POST 请求出现异常！", e);
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				logger.error("关闭流异常", ex);
			}
		}
		return result;
	}
	/**
	 * 获取分页参数
	 *
	 * @param map
	 * @throws Exception
	 */
	public static Map<String, Object> getPageParams(Map<String, Object> map) {
		String pageSizeStr = String.valueOf(map.get("pageSize"));
		String pageNumStr = String.valueOf(map.get("pageNum"));
		if (StringUtil.isEmpty(pageSizeStr)
				|| "0".equals(pageSizeStr)) {
			pageSizeStr = "10";
		}
		if (StringUtil.isEmpty(pageNumStr)
				|| "0".equals(pageNumStr)) {
			pageNumStr = "1";
		}

		int rowBegin = (Integer.parseInt(pageNumStr) - 1)
				* Integer.parseInt(pageSizeStr);
		int rowEnd = Integer.parseInt(pageSizeStr);

		map.put("rowBegin", rowBegin);
		map.put("rowEnd", rowEnd);
		map.put("pageSize", rowEnd);
		map.put("pageNum", pageNumStr);
		return map;
	}
}